/*
 * android http操作类
 * 利用HttpUrlConnection类实现http get,post操作
 * @date 2009-11-6
 * @author weixk
 * 
 * @!!!! 注意在调用本类的时候，需要开启android.permission.INTERNET的uesr-permission !!!!
 */

package com.looso.sfolder.net;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpConnectionDemo {
	
	/*
	 * 构造方法
	 */
	public HttpConnectionDemo(){
		
	}
	
	/**
	* 向指定URL发送GET方法的https请求
	* @param url 发送请求的URL
	* @return String 返回的网络数据
	*/
	public static byte[] sendHttpsPost(String url,byte[] requestContent)
	{
		ByteArrayOutputStream out = null;
		InputStream inputStream = null;
		try
		{
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, new TrustManager[]{new MyTrustManager()},new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
			
			String urlName = url;
			URL realUrl = new URL(urlName);
					
			//1.初始化并建立连接
			//打开和URL之间的连接
			HttpsURLConnection conn = (HttpsURLConnection)realUrl.openConnection();
			//post方法需要设置doinput和doOutput为true
			conn.setDoInput(true);
			conn.setDoOutput(true);
			//设置http header		
			conn.setRequestProperty("Accept", "text/json");
			conn.setRequestProperty("Content-Length", ""+requestContent.length);//!!设置http body length,post必须包含的http头
			//2.设置超时	
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			//设置http header
			//建立实际的连接
			conn.connect(); 			
			
			
			//3.建立连接，发送输出流
			//建立输出流，发送post数据
			OutputStream outputStream = conn.getOutputStream();
			outputStream.write(requestContent);
			outputStream.flush();  //把流缓冲区中的当前全部内容强制输出

			//4.得到服务端回复
			//得到http的响应，如果responseCode=HttpConnection.HTTP_OK，即请求成功
//			int responseCode = conn.getResponseCode();
//			String responseMessage = conn.getResponseMessage();			
			//得到网络数据流
			inputStream = conn.getInputStream();
			
			//4.对获取的数据流进行处理
			//定义BufferedReader输入流来读取URL的响应,保存在result里
			out = new ByteArrayOutputStream(1024);
			byte[] temp = new byte[1024];			
			int size = 0;			
			while ((size=inputStream.read(temp))!=-1) {
				out.write(temp,0,size);			
			}
						
//			in = new BufferedReader(new InputStreamReader(inputStream));
//			String line;
//			while ((line = in.readLine())!= null){
//				result += "\n" + line;
//			}
		}	
		catch(Exception e){
			System.out.println("发送post请求出现异常！" + e);
			e.printStackTrace();
		}
		//5.使用finally块来关闭输入流
		finally{
			try{
				if(inputStream != null){
					inputStream.close();
				}
			}
			catch (IOException ex){
				ex.printStackTrace();
			}
		}
		
		if(out!=null){
			return out.toByteArray();
		}else{
			return null;
		}
	}
	
	/**
	* 向指定URL发送GET方法的https请求
	* @param url 发送请求的URL
	* @return String 返回的网络数据
	*/
	public static byte[] sendHttpsGet(String url)
	{
//		BufferedReader in = null;
		ByteArrayOutputStream out = null;
		InputStream inputStream = null;
		try
		{
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, new TrustManager[]{new MyTrustManager()},new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
			
			String urlName = url;
			URL realUrl = new URL(urlName);
					
			//1.初始化并建立连接
			//打开和URL之间的连接
			HttpsURLConnection conn = (HttpsURLConnection)realUrl.openConnection();
			//2.设置超时	
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			//设置http header
			//建立实际的连接
			conn.connect(); 			
			
			//3.获取数据流
			//得到网络数据流
			inputStream = conn.getInputStream();
			
			//4.对获取的数据流进行处理
			//定义BufferedReader输入流来读取URL的响应,保存在result里
			out = new ByteArrayOutputStream(1024);
			byte[] temp = new byte[1024];			
			int size = 0;			
			while ((size=inputStream.read(temp))!=-1) {
				out.write(temp,0,size);			
			}
						
//			in = new BufferedReader(new InputStreamReader(inputStream));
//			String line;
//			while ((line = in.readLine())!= null){
//				result += "\n" + line;
//			}	        	        						
		}	
		catch(Exception e){
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		//5.使用finally块来关闭输入流
		finally{
			try{
				if(inputStream != null){
					inputStream.close();
				}
			}
			catch (IOException ex){
				ex.printStackTrace();
			}
		}
		
		if(out!=null){
			return out.toByteArray();
		}else{
			return null;
		}
	}
	
	private static class MyHostnameVerifier implements HostnameVerifier{
		@Override
		public boolean verify(String hostname, SSLSession session) {
			// TODO Auto-generated method stub
			return true;
		}		
	}
	
	private static class MyTrustManager implements X509TrustManager{
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
		
	}
	
	
    /**
	* 向指定URL发送GET方法的请求
	* @param url 发送请求的URL
	* @return String 返回的网络数据
	*/
	public static byte[] sendGet(String url)
	{
		BufferedReader in = null;
		ByteArrayOutputStream out = null;
		try
		{			
			String urlName = url;
			URL realUrl = new URL(urlName);
			
			//1.设置超时
			//设置连接主机的超时时间,(单位毫秒)
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
			//设置从主机读取数据的超时时间,(单位毫秒)
			System.setProperty("sun.net.client.defaultReadTimeout", "30000");			
			
			//2.初始化并建立连接
			//打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			//设置http header
			conn.setRequestProperty("Accept", "text/xml");
			//建立实际的连接
			conn.connect(); 
			//获取所有响应头字段
			Map<String,List<String>> map = conn.getHeaderFields();
			//遍历所有的响应头字段
			for (String key : map.keySet()){
				System.out.println(key + "--->" + map.get(key));
			}
			
			//3.获取数据流
			//得到网络数据流
			InputStream inputStream = conn.getInputStream();
			
			//4.对获取的数据流进行处理
			//定义BufferedReader输入流来读取URL的响应,保存在result里
			out = new ByteArrayOutputStream(1024);
			byte[] temp = new byte[1024];			
			int size = 0;			
			while ((size=inputStream.read(temp))!=-1) {
				out.write(temp,0,size);			
			}
						
//			in = new BufferedReader(new InputStreamReader(inputStream));
//			String line;
//			while ((line = in.readLine())!= null){
//				result += "\n" + line;
//			}	        	        						
		}	
		catch(Exception e){
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		//5.使用finally块来关闭输入流
		finally{
			try{
				if (in != null){
					in.close();
				}
			}
			catch (IOException ex){
				ex.printStackTrace();
			}
		}
		
		return out.toByteArray();
	}
	
	/**
	* 向指定URL发送GET方法的请求
	* @param url 发送请求的URL
	* @return String 返回的网络数据
	*/
	public static InputStream sendHttpsGetInputStream(String url)
	{		
		try
		{
			//url = "https://172.20.206.135/";
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, new TrustManager[]{new MyTrustManager()},new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
			
			URL realUrl = new URL(url);
					
			//2.初始化并建立连接
			//打开和URL之间的连接
			HttpsURLConnection conn = (HttpsURLConnection)realUrl.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			//设置http header
			//conn.setRequestProperty("Accept", "text/xml");
			//建立实际的连接
			conn.connect(); 			
			
			//3.获取数据流
			//得到网络数据流
			InputStream inputStream = conn.getInputStream();
			return inputStream;
		}	
		catch(Exception e){
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
			return null;
		}		
	}
	
	
    /**
	* 向指定URL发送POST方法的请求
	* @param url 发送请求的URL
	* @param requestConnect post的数据body
	* @return String 返回的网络数据
	*/
	public static String sendPost(String url,byte[] requestContent){
		
		String result = "";
		BufferedReader in = null;
		
		try {			
			String urlName = url;
			URL realUrl = new URL(urlName);		
			//1.设置超时			
			//设置连接主机的超时时间,(单位毫秒)
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
			//设置从主机读取数据的超时时间,(单位毫秒)
			System.setProperty("sun.net.client.defaultReadTimeout", "30000");
			
			//2.初始化连接
			//打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();			
			//post方法需要设置doinput和doOutput为true
			connection.setDoInput(true);
			connection.setDoOutput(true);			
			//设置http header		
			connection.setRequestProperty("Accept", "text/xml");
			connection.setRequestProperty("Content-Length", ""+requestContent.length);//!!设置http body length,post必须包含的http头		
			
			//3.建立连接，发送输出流
			//建立输出流，发送post数据
			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(requestContent);
			outputStream.flush();  //把流缓冲区中的当前全部内容强制输出

			//4.得到服务端回复
			//得到http的响应，如果responseCode=HttpConnection.HTTP_OK，即请求成功
//			int responseCode = connection.getResponseCode();
//			String responseMessage = connection.getResponseMessage();			
			//得到网络数据流
			InputStream inputStream = connection.getInputStream();
			
			//5.对获取的数据流进行处理
			//定义BufferedReader输入流来读取URL的响应,保存在result里
			in = new BufferedReader(new InputStreamReader(inputStream));
			String line;
			while ((line = in.readLine())!= null)
			{
				result += "\n" + line;
			}			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		//6.使用finally块来关闭输入流
		finally{
			try{
				if (in != null){
					in.close();
				}
			}
			catch (IOException ex){
				ex.printStackTrace();
			}
		}
		
		return result;
	}
	
	
}
